using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using LeisureCenter.Api;
using LeisureCenter.Core;
using LeisureCenter.Forms;
using LeisureCenter.Controls;

namespace LeisureCenter.OptionsForms
{
    public partial class LibraryObjectOptionsDialog : LeisureCenter.Forms.DialogControl
    {
        private string fileName;

        public LibraryObjectOptionsDialog(string fileName)
        {
            InitializeComponent();
            this.fileName = fileName;
        }

        private long libraryId;

        public long LibraryId
        {
            get { return libraryId; }
            set
            {
                libraryId = value; 
                btnLibrary.Text = DatabaseManager.ExecuteStringScalar(@"SELECT name FROM Libraries WHERE id = " + libraryId, @"<<none>>");
            }
        }

        private void btnLibrary_Click(object sender, EventArgs e)
        {
            List<string> items = new List<string>();
            items.AddRange(DatabaseManager.ExecuteStringsQuery("SELECT name FROM Libraries"));
            items.Add("Create new...");
            int index = items.IndexOf(btnLibrary.Text);
            if (ListDialog.Execute(items, true, ref index, Color.White))
            {
                if (index != items.Count - 1)
                {
                    LibraryId = DatabaseManager.ExecuteLongScalar(string.Format(@"SELECT id FROM Libraries WHERE name = '{0}'", items[index]), libraryId);
                }
                else
                {
                    string name = "";
                    if (VirtualKeyboardDialog.Execute(@"Enter the name of the new library:", ref name) && !string.IsNullOrEmpty(name))
                    {
                        LibraryId = DatabaseManager.ExecuteLongScalar(string.Format(@"INSERT INTO Libraries (name) values ('{0}'); SELECT last_insert_rowid();", name), libraryId);
                    }
                }
            }
        }

        public override void SetFocusHandlers(IFocusHandler okButton, IFocusHandler cancelButton)
        {
            ratingBar1.FocusDown = okButton;
            btnPlayed.FocusUp = okButton;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Program.LeisureCenterInstance.libraryManager.filesCheckerThread.AddFile(new FileInfo(this.fileName), true);
            Program.LeisureCenterInstance.libraryManager.filesCheckerThread.Wakeup();
        }

        private void btnPlaylists_Click(object sender, EventArgs e)
        {
            List<KeyValuePair<string, long>> removeFromPlaylists = new List<KeyValuePair<string,long>>(DatabaseManager.ExecuteStringsLongsQuery(string.Format(@"SELECT Playlists.Name, Playlists.Id FROM Playlists, PlaylistsItems, Files WHERE Playlists.Id = PlaylistsItems.PlaylistId AND PlaylistsItems.FileId = Files.id AND Files.filename = '{0}' AND Files.libraryId = {1}", this.fileName, this.libraryId)));
            List<KeyValuePair<string, long>> addToPlaylists = new List<KeyValuePair<string, long>>(DatabaseManager.ExecuteStringsLongsQuery(string.Format(@"SELECT Playlists.Name, Playlists.Id FROM Playlists WHERE Playlists.libraryId = {1} AND Playlists.id NOT IN (SELECT PlaylistsItems.PlaylistId FROM PlaylistsItems, Files WHERE PlaylistsItems.FileId = Files.id AND Files.filename = '{0}')", this.fileName, this.libraryId)));
            List<string> items = new List<string>();
            foreach (KeyValuePair<string, long> item in removeFromPlaylists)
            {
                items.Add(string.Format(@"Remove from '{0}'", item.Key));
            }
            foreach (KeyValuePair<string, long> item in addToPlaylists)
            {
                items.Add(string.Format(@"Add to '{0}'", item.Key));
            }
            items.Add(@"Add to new playlist...");
            int index = 0;
            if (ListDialog.Execute(items, true, ref index, Color.Chocolate))
            {
                long fileId = DatabaseManager.ExecuteLongScalar(string.Format("SELECT id FROM Files WHERE filename = '{0}'", this.fileName), 0);
                if (fileId == 0)
                    return;

                if (index < removeFromPlaylists.Count)
                {
                    // remove from playlist
                    long id = removeFromPlaylists[index].Value;
                    DatabaseManager.ExecuteNonQuery(string.Format(@"DELETE FROM PlaylistsItems WHERE playlistId = {0} AND fileId = {1}", id, fileId));
                }
                else
                {
                    long id = 0;
                    if (index < removeFromPlaylists.Count + addToPlaylists.Count)
                    {
                        // add to playlist
                        id = addToPlaylists[index - removeFromPlaylists.Count].Value;
                    }
                    else
                    {
                        // add to new playlist
                        string name = "";
                        if (VirtualKeyboardDialog.Execute(@"Enter new playlist name:", ref name) && !string.IsNullOrEmpty(name))
                        {
                            id = DatabaseManager.ExecuteLongScalar(string.Format(@"INSERT INTO Playlists (name, libraryId) VALUES ('{0}', {1}); SELECT last_insert_rowid();", name, this.libraryId), 0);
                        }
                    }
                    DatabaseManager.ExecuteNonQuery(string.Format(@"INSERT INTO PlaylistsItems (playlistId, fileId) VALUES ({0}, {1})", id, fileId));
                }
            }
        }

        private void btnPlayed_Click(object sender, EventArgs e)
        {
            long fileId = DatabaseManager.ExecuteLongScalar(string.Format("SELECT Id FROM Files WHERE Filename = '{0}'", this.fileName), 0);
            if (fileId == 0)
                return;
            DatabaseManager.ExecuteNonQuery(string.Format("INSERT INTO Playings (Id, Datetime) VALUES ({0}, {1})", fileId, DateTime.Now.ToFileTime()));
        }
    }
}